version 19
drop _all

* change the root folder according to your computer directory
global root = "D:\WorkingPaper-Series\Township_Light\Replication_Files"  

global dofiles = "$root\dofile"     
global working_data = "$root\workdata"
global tables = "$root\table"
global figures = "$root\figure"

cd "$working_data"


******************
*****Pre Set******
******************

global geo_ctrl = "topography_t* slope_t* roughness_t*"
global wth_ctrl = "gaez_t* precipitation_t* sunlight_t*"
global dist_ctrl = "county_dist_t* dist_hz_t* dist_coast_t*"

global full_ctrl = "$geo_ctrl $wth_ctrl $dist_ctrl"

global geo_ctrl_1 = "topography_t_1 slope_t_1 roughness_t_1"
global wth_ctrl_1 = "gaez_t_1 precipitation_t_1 sunlight_t_1"
global dist_ctrl_1 = "county_dist_t_1 dist_hz_t_1 dist_coast_t_1"

global full_ctrl_1 = "$geo_ctrl_1 $wth_ctrl_1 $dist_ctrl_1"

global geo_ctrl_2 = "topography_t_2 slope_t_2 roughness_t_2"
global wth_ctrl_2 = "gaez_t_2 precipitation_t_2 sunlight_t_2"
global dist_ctrl_2 = "county_dist_t_2 dist_hz_t_2 dist_coast_t_2"

global full_ctrl_2 = "$geo_ctrl_2 $wth_ctrl_2 $dist_ctrl_2"

global matchvar = "county_dist topography slope gaez sunlight dist_hz dist_coast"


global pre_ctrl = "light_t road_t pop_t"

********************
***** Figure 6 *****
********************

use "township_panel_final.dta", clear

foreach w in topography county_dist fiscal_pressure road13 county_gdp_pc light10 population10 {
	mat define est_`w' = J(4,2,0)
	egen `w'_ptile = xtile(`w'), n(4)
	sum `w'_ptile
	forvalues i = 1 (1) `r(max)' {
	gen vil_`w'_`i' = village*(`w'_ptile==`i')
	}
	reghdfe log_light vil_`w'_* treat_trend $full_ctrl, a(county_year idcode) cl(countycode)
	forvalues i = 1 (1) 4 {
		mat est_`w'[`i',1] = e(b)[1,`i']
		mat est_`w'[`i',2] = sqrt(e(V)[`i',`i'])
	}
}

foreach w in topography county_dist fiscal_pressure road13 county_gdp_pc light10 population10 {
	svmat est_`w'
	rename (est_`w'1 est_`w'2) (coef_`w' se_`w')
}

keep coef* se_*
keep in 1/4
gen quantile = _n

reshape long coef se, i(quantile) j(type) string
sort type quantile

export delimited using "hetero_est.csv", replace
